#include "tga.h"
#include "../texture.h"
#include <stdlib.h>

namespace sleek
{
    namespace texture
    {
        texture* LoadTextureFromTga(core::os::stringc file)
        {
            GLubyte TGAheader[12]= {0,0,2,0,0,0,0,0,0,0,0,0};
            GLubyte out[12], header[6];

            FILE *in = fopen(file.c_str(), "rb");
            if (fread(out,1,sizeof(out),in)!=sizeof(out)){ return 0; };
            if (memcmp(TGAheader,out,sizeof(TGAheader))!=0){ return 0; };
            if (fread(header,1,sizeof(header),in)!=sizeof(header)){ return 0; };
            fclose (in);

            texture *tex = new texture(core::math::vector2du(header[1]*256+header[0], header[3]*256+header[0]), (TextureFormat)header[4]);

            for (register unsigned int i = 0; i < tex->getOriginalSize().width*tex->getOriginalSize().height*tex->getFormat()/8; i += tex->getFormat()/8 )
            {
                int t = tex->buffer[i];
                tex->buffer[i] = tex->buffer[i+2];
                tex->buffer[i+2] = t;
            }

            return tex;
        }
        bool WriteTextureToTga(texture*,core::os::stringc)
        {
        }
        bool IsTextureFormatTga(core::os::stringc file)
        {
            GLubyte TGAheader[12]= {0,0,2,0,0,0,0,0,0,0,0,0};
            GLubyte out[12], header[6];

            FILE *in = fopen(file.c_str(), "rb");
            if (fread(out,1,sizeof(out),in)!=sizeof(out)){ return false; };

            if (memcmp(TGAheader,out,sizeof(TGAheader))==0)
                return true;

            return false;
        }
    }
}
